import subprocess
import os
import signal


def get_pid_using_port(port):
    try:
        result = subprocess.check_output(f"lsof -ti :{port}", shell=True)
        return result.decode().strip()
    except subprocess.CalledProcessError:
        return None


def kill_process(pid):
    try:
        os.system(f"kill -9 {pid}")
        print(f"进程 {pid} 已被终止。")
    except ProcessLookupError:
        print(f"进程 {pid} 不存在，可能已经被终止。")
    except PermissionError:
        print("没有足够的权限终止进程。")
    except Exception as e:
        print(f"终止进程时发生错误: {e}")


def delete_port(port):
    pid = get_pid_using_port(port)

    if pid:
        print(f"端口 {port} 被进程 {pid} 占用，准备终止...")
        kill_process(pid)
    else:
        print(f"没有进程占用端口 {port}。")
